from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def hello_world():
    driver = webdriver.Chrome()
    driver.get("http://www.python.org")
    assert "Python" in driver.title
    elem = driver.find_element_by_name("q")
    elem.clear()
    elem.send_keys("pycon")
    elem.send_keys(Keys.RETURN)
    assert "No results found." not in driver.page_source
    print(driver.page_source)
    driver.close()


def switch_new_page(browser):
    print(browser.current_window_handle)            # 输出当前窗口句柄（百度）
    handles = browser.window_handles                # 获取当前窗口句柄集合（列表类型）
    print(handles)                                  # 输出句柄集合

    for handle in handles:                          # 切换窗口（切换到搜狗）
        if handle != browser.current_window_handle:
            print('switch to ', handle)
            browser.switch_to_window(handle)
            print(browser.current_window_handle)    # 输出当前窗口句柄（搜狗）
            break


if __name__ == '__main__':
    driver = webdriver.Chrome()
    try:
        wait = WebDriverWait(driver,10)

        driver.get("https://www.baidu.com/")

        elem = driver.find_element_by_id('kw')
        #模拟输入Python，进行搜索
        elem.send_keys('python')
        elem.submit()

        # 等待浏览器刷新，返回我们的搜索结果
        WebDriverWait(driver, 10).until(EC.title_contains("python"))

        # 输出当前浏览器的标题
        print(driver.title)

        rs = wait.until(EC.presence_of_element_located((By.ID, 'content_left')))
        all_options = rs.find_elements_by_xpath(".//div[@class='result c-container ']")
        for item in all_options:
            aurls = item.find_elements_by_tag_name('a')
            for aurl in aurls:
                print(aurl.get_property('text') + "\t" + aurl.get_property('href'))

        all_options[0].find_elements_by_tag_name('h3')[0].find_elements_by_tag_name('a')[0].click()
        print(all_options[0].find_elements_by_tag_name('a')[0].get_property('text'))

        time.sleep(3)
        switch_new_page(driver)

        wait.until(EC.title_contains("Python.org"))

        # 输出当前浏览器的标题
        print(driver.title)

    except Exception as ve:
        print(ve)

    driver.close()
    driver.quit()
